#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
@FileName  :adminSerializers.py.py 
@desc      :定义序列化器
@Author    :Young
@IDE       :PyCharm
@Time      :2021/6/11 0011 23:03
'''
from rest_framework.serializers import ModelSerializer
from Admin.models import Admin_User, Article_comment, Article_theme,Articles,Q_Answer,Q_answer_comment,Question_theme,Questions,\
    Dis_answer, Dis_topic, Discussion_groups, User
from rest_framework import serializers


#登录的序列化器
#登录序列化
class LoginSerializer(serializers.Serializer):
    admin_name = serializers.CharField(min_length=3,required=True)
    admin_password = serializers.CharField(required=True,min_length=3)
    def validate(self, attrs):
        #获取和密管理员码
        name = attrs.get('admin_name')
        password = attrs.get('admin_password')
        #查询管理员是否存在于数据库中
        administrator = Admin_User.objects.filter(admin_name=name)
        if not administrator.exists():  #判断该用户是否存在
            raise serializers.ValidationError({'name':"该用户不存在"})  #抛出异常
        #用户存在
        admin = administrator.first()
        print(admin)
        #验证密码是否正确
        # check_password(password, user.u_password)   第一个参数是明文密码，第二个参数是签名过后的密码 如果二者相等 返回True
        if password != admin.admin_password:
            raise serializers.ValidationError({'invalid':'用户名或密码错误'})

        #如果上面的两项都不报错，将attrs返回
        return attrs


class AdminSerializer(ModelSerializer):
    class Meta:
        model = Admin_User
        fields = "__all__"


class  UserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"

class ArticleThemeSerializer(ModelSerializer):
    class Meta:
        model = Article_theme
        fields = "__all__"



class ArticleCommentSerializer(ModelSerializer):
    class Meta:
        model = Article_comment
        fields = "__all__"

class QuestionThemeSerializer(ModelSerializer):
    class Meta:
        model = Question_theme
        fields = "__all__"


class QAnswerSerializer(ModelSerializer):
    class Meta:
        model = Q_Answer
        fields = "__all__"

class QAnswer_commentSerializer(ModelSerializer):
    class Meta:
        model = Q_answer_comment
        fields = "__all__"

class DisTopicSerializer(ModelSerializer):
    class Meta:
        model = Dis_topic
        fields = "__all__"

class DisAnswerSerializer(ModelSerializer):
    class Meta:
        model = Dis_answer
        fields = "__all__"

class ArticlesSerializer(ModelSerializer):
    article_theme_id = ArticleThemeSerializer()
    article_author_id = UserSerializer()
    class Meta:
        model = Articles
        fields = "__all__"


class QuestionsSerializer(ModelSerializer):
    q_theme_id = QuestionThemeSerializer()
    class Meta:
        model = Questions
        fields = "__all__"

class DisGroupSerializer(ModelSerializer):
    dis_topic_id = DisTopicSerializer()
    class Meta:
        model = Discussion_groups
        fields = "__all__"